'''
Created on Mar 31, 2011

@author: leo
'''

import config
import urllib2
import uuid
import http # milti-form 

HEADER_AUTHENTICATION_KEY = 'Authorization'
class GoogleCloudPrint():
    '''
    provide interfaces to fetch data from google cloud print
    '''
    
    def __init__(self, user, client='eMail Print'):
        self.user = user
        self.client = client
        self.config = config.Config('https://www.google.com/cloudprint/')
        
    def search_printers(self):
        request = urllib2.Request(self.config.google_search_printers_url())
        request.add_header(HEADER_AUTHENTICATION_KEY, '%s %s' % ('OAuth', self.user.get_access_token()))
        opener = urllib2.build_opener()
        return opener.open(request).read()
        
    
    def get_printer_info(self, printerid):
        request = urllib2.Request(self.config.google_get_printer_info_url(printerid))
        request.add_header(HEADER_AUTHENTICATION_KEY, '%s %s' % ('OAuth', self.user.get_access_token()))
        opener = urllib2.build_opener()
        return opener.open(request).read()

    def submit_print_job(self, printerid, contentType, content, title=None, capabilities='{"capabilities":[]}'):
        if(title is None):
            title = str(uuid.uuid4())
        
        fields = {
                  'printerid': printerid,
                  'contentType': contentType,
                  'content': content,
                  'title': title,
                  'capabilities': capabilities,
                  }

        request = urllib2.Request(url=self.config.google_submit_print_job_url())
        request.add_header(HEADER_AUTHENTICATION_KEY, '%s %s' % ('OAuth', self.user.get_access_token()))
        opener = urllib2.build_opener(http.MultipartPostHandler)
        return opener.open(request, fields).read()

